﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Events;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Shipping;
using Nop.Web.Areas.App.Models;
using Nop.Web.Factories;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Mvc.Filters;
using Nop.Web.Framework.Security;
using Nop.Web.Services.Factories;

namespace Nop.Web.Areas.App.Controllers
{
    public class OrderController : BaseAppController
    {
        #region Fields

        private readonly IOrderModelFactory _orderModelFactory;
        private readonly IOrderProcessingService _orderProcessingService;
        private readonly IOrderService _orderService;
        private readonly IPaymentService _paymentService;
        private readonly IPdfService _pdfService;
        private readonly IShipmentService _shipmentService;
        private readonly IWebHelper _webHelper;
        private readonly IWorkContext _workContext;
        private readonly RewardPointsSettings _rewardPointsSettings;
        private readonly IStoreContext _storeContext;
        private readonly HUCFactory _hUCFactory;
        private readonly IEventPublisher _eventPublisher;
        private readonly IProductService _productService;
        #endregion

        #region Ctor

        public OrderController(IOrderModelFactory orderModelFactory,
            IOrderProcessingService orderProcessingService,
            IOrderService orderService,
            IPaymentService paymentService,
            IPdfService pdfService,
            IShipmentService shipmentService,
            IWebHelper webHelper,
            IWorkContext workContext,
            RewardPointsSettings rewardPointsSettings,
            IStoreContext storeContext,
            HUCFactory hUCFactory, 
            IEventPublisher eventPublisher,
            IProductService productService)
        {
            this._orderModelFactory = orderModelFactory;
            this._orderProcessingService = orderProcessingService;
            this._orderService = orderService;
            this._paymentService = paymentService;
            this._pdfService = pdfService;
            this._shipmentService = shipmentService;
            this._webHelper = webHelper;
            this._workContext = workContext;
            this._rewardPointsSettings = rewardPointsSettings;
            this._storeContext = storeContext;
            this._hUCFactory = hUCFactory;
            this._eventPublisher = eventPublisher;
            this._productService = productService;
        }

        #endregion

        public IActionResult List()
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
                return Json(new AppResult
                {
                    Code = 999,
                    Message = "您还没有登录"
                });

            var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id);

            var orderModels = orders.Select(o => _orderModelFactory.PrepareOrderDetailsModel2(o)).ToList();

            return Json(new AppResult
            {
                Result = new { Orders = orderModels }
            });
        }

        public IActionResult Details(int orderId)
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
                return Json(new AppResult
                {
                    Code = 999,
                    Message = "您还没有登录"
                });
            var order = _orderService.GetOrderById(orderId);
            if (order == null)
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "订单不存在"
                });
            if (order.CustomerId != _workContext.CurrentCustomer.Id)
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "订单不属于当前用户"
                });
            return Json(new AppResult
            {
                Result = new
                {
                    Order = _orderModelFactory.PrepareOrderDetailsModel2(order, false),
                    ShipProcessHours = 15 * 24,
                    PaymentTimeOutHours = 24
                }
            });
        }

        public IActionResult SetAsDelivered(int orderId)
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
                return Json(new AppResult
                {
                    Code = 999,
                    Message = "您还没有登录"
                });
            var order = _orderService.GetOrderById(orderId);
            if (order.CustomerId != _workContext.CurrentCustomer.Id)
            {
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "该订单不属于您"
                });
            }
            foreach (var shipment in order.Shipments)
            {
                if (!shipment.DeliveryDateUtc.HasValue)
                {
                    order.OrderNotes.Add(new OrderNote()
                    {
                        Note = $"用户包裹[{shipment.Id}]收货已被用户设为收货状态",
                        DisplayToCustomer = true,
                        CreatedOnUtc = DateTime.UtcNow
                    });
                    _orderProcessingService.Deliver(shipment, false);
                }
            }
            _hUCFactory.CalcOrderCount(order);
            var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id);

            var orderModels = orders.Select(o => _orderModelFactory.PrepareOrderDetailsModel2(o)).ToList();

            return Json(new AppResult
            {
                Result = new { Orders = orderModels }
            });
        }

        public IActionResult CancelOrder(int orderId)
        {

            if (!_workContext.CurrentCustomer.IsRegistered())
                return Json(new AppResult
                {
                    Code = 999,
                    Message = "您还没有登录"
                });
            var order = _orderService.GetOrderById(orderId);
            if (order.CustomerId != _workContext.CurrentCustomer.Id)
            {
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "该订单不属于您"
                });
            }
            order.OrderNotes.Add(new OrderNote()
            {
                Note = $"客户取消订单",
                DisplayToCustomer = true,
                CreatedOnUtc = DateTime.UtcNow
            });
            _orderProcessingService.CancelOrder(order, false);
            var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id);

            var orderModels = orders.Select(o => _orderModelFactory.PrepareOrderDetailsModel2(o)).ToList();

            return Json(new AppResult
            {
                Result = new { Orders = orderModels }
            });
        }

        public IActionResult OrderReviews(int orderId, List<OrderProductReviews> reviews)
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
                return Json(new AppResult
                {
                    Code = 999,
                    Message = "您还没有登录"
                });
            var order = _orderService.GetOrderById(orderId);
            if (order.CustomerId != _workContext.CurrentCustomer.Id)
            {
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "该订单不属于您"
                });
            }
            if (order.OrderStatus != OrderStatus.Complete)
            {
                return Json(new AppResult
                {
                    Code = 500,
                    Message = "该订单还未完成"
                });
            }

            foreach (var item in reviews)
            {
                var product = _productService.GetProductById(item.ProductId);
                var productReview = new ProductReview
                {
                    ProductId = product.Id,
                    CustomerId = _workContext.CurrentCustomer.Id,
                    Title = "默认标题",
                    ReviewText = item.ReviewText,
                    Rating = item.Rating,
                    HelpfulYesTotal = 0,
                    HelpfulNoTotal = 0,
                    IsApproved = true,
                    CreatedOnUtc = DateTime.UtcNow,
                    StoreId = _storeContext.CurrentStore.Id,
                };

                product.ProductReviews.Add(productReview);

                //update product totals
                _productService.UpdateProductReviewTotals(product);

                _eventPublisher.Publish(new ProductReviewApprovedEvent(productReview));
            }

            var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id);

            var orderModels = orders.Select(o => _orderModelFactory.PrepareOrderDetailsModel2(o)).ToList();

            return Json(new AppResult
            {
                Result = new { Orders = orderModels }
            });

        }
    }
}
